<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="购物车"
        @click-left="$router.go(-1)"
        left-arrow
      ></van-nav-bar>
    </header>
    <div class="content">
      <div class="noshop" v-if="shopFlag">
        <img src="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png" alt="">
        <h3>
          您的购物车空空如也，请<router-link to="/home">选择商品</router-link>
        </h3>
      </div>
      <div class="shopping" v-else>
        <van-notice-bar
          color="black"
          text="您正在安全购物环境中，请放心购买"
        ></van-notice-bar>
        <van-icon class="anquan" name="after-sale" size="24"/>
        <van-swipe-cell v-for="(item, index) of cartlist" :key="item.cardid">
          <van-card
            :price="item.price"
            :title="item.proname"
          >
            <template #thumb>
              <input type="checkbox" v-model="item.flag" @change="selectItem(item, $event)">
              <img :src="item.proimg" alt="">
            </template>
            <template #tags>
              <van-tag plain type="danger">{{ item.brand }}</van-tag>
            </template>
            <template #footer>
              <van-button class="jian" :disabled="item.num <= 1" size="mini" @click="reduce(item)">-</van-button>
              <van-button class="shuliang" disabled size="mini">{{ item.num }}</van-button>
              <van-button class="jia" size="mini" @click="add(item)">+</van-button>
            </template>
          </van-card>
          <van-icon
            name="cross"
            class="delete-button"
            @click="deleteItem(item.cartid, index)"
          />
        </van-swipe-cell>
        <van-submit-bar
          :price="totalPrice * 100"
          :button-text="'去结算(' + totalNum +')'"
          @submit="onSubmit"
        >
          <van-checkbox v-model="allchecked" @click="selectAll">全选</van-checkbox>
            <!-- <template #tip>
                你的收货地址不支持同城送, <span @click="onClickEditAddress">修改地址</span>
            </template> -->
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { getCartData, updateCartData, deleteCartData, addOrder } from '@/api'
import { NavBar, Card, Tag, Button, SwipeCell, NoticeBar, Dialog, SubmitBar, Checkbox, Toast, Icon } from 'vant'
Vue.use(NavBar)
Vue.use(Card)
Vue.use(Tag)
Vue.use(Button)
Vue.use(SwipeCell)
Vue.use(NoticeBar)
Vue.use(Dialog)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(Toast)
Vue.use(Icon)
export default {
  data () {
    return {
      cartlist: [],
      allchecked: true
    }
  },
  computed: {
    shopFlag () {
      return this.cartlist.length === 0
    },
    totalPrice () {
      return this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.price * item.num : sum + 0
      }, 0)
    },
    totalNum () {
      return this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.num : sum + 0
      }, 0)
    }
  },
  mounted () {
    getCartData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      this.cartlist = res.data.data
    })
  },
  methods: {
    add (item) {
      // item.num += 1
      updateCartData({ cartid: item.cartid, num: item.num + 1 }).then(res => {
        // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          item.num += 1 // 修改页面
        }
      })
    },
    reduce (item) {
      // item.num -= 1
      updateCartData({ cartid: item.cartid, num: item.num > 1 ? item.num - 1 : 1 }).then(res => {
        // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          // item.num -= 1 // 修改页面
          item.num > 1 ? item.num -= 1 : item.num = 1
        }
      })
    },
    deleteItem (cartid, index) {
      Dialog.confirm({
        title: '删除',
        message: '删掉的商品可能被别人抢走哦，要删除吗？'
      }).then(() => {
        // on confirm
        deleteCartData({ cartid }).then(res => {
          if (res.data.code === '200') {
            // 修改状态
            this.cartlist.splice(index, 1)
          }
        })
      }).catch(() => {
        // on cancel
      })
    },
    selectItem (item, event) {
      console.log(item)
      console.log(event.target.checked)
      // 后端实现接口，给后端传入cartod 以及 event.target.checked，如果成功执行以下操作
      item.flag = event.target.checked
      if (event.target.checked) {
        this.allchecked = this.cartlist.every(item => {
          return item.flag
        })
      } else {
        this.allchecked = false
      }
    },
    selectAll (event) {
      this.allchecked = !this.allchecked
      // if (checked) {
      //   this.cartlist.map(item => {
      //     item.flag = true
      //   })
      // } else {
      //   this.cartlist.map(item => {
      //     item.flag = false
      //   })
      // }
      this.cartlist.map(item => {
        item.flag = this.allchecked
      })
    },
    onSubmit () {
      // 需要判定有没有选中商品,没有给予提示
      if (this.totalNum === 0) {
        Toast.fail('请先勾选你要购买的东西')
      } else {
        // Toast('确认订单')
        const arr = []
        this.cartlist.map(item => {
          if (item.flag) {
            arr.push(item)
          }
        })
        addOrder({
          userid: localStorage.getItem('userid'),
          // 选中商品即为 arr
          orderlist: JSON.stringify(arr)
        }).then(res => {
          console.log(res)
          // 返回一个订单id,跳转页面传递订单id
          this.$router.push('/order/' + res.data.orderid)
        })
      }
    }
  }
}
</script>

<style lang="scss">
.van-nav-bar {
  color:#575757;
}
.van-notice-bar {
  text-indent: 20px;
  background-color: #e8eaf4;
}
.anquan {
  color: green;
  position: relative;
  left: 10px;
  top: -32px;
}
.delete-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
  font-size: 24px;
}
.noshop {
  margin-top: 30px;
  text-align: center;
  img {
    width: 100px;
  }
}
.van-card {
  position: relative;
  height: 130px;
}
.van-card__content {
  min-width: 55px;
}
.van-card__thumb {
  input {
    display: block;
    width: 10px;
    margin-top: 50%;
    transform: translateY(-50%);
    float: left;
  }
  img {
    display: block;
    width: 70px;
    float: left;
    border-radius: 1px;
  }
}
.van-card__footer {
  position: relative;
  left: 70px;
  top: 0px;
  .jian {
    height: 25px;
    font-size: 24px;
    position: absolute;
    left: 10px;
    top: 0;
  }
  .shuliang {
    height: 25px;
    font-size: 20px;
    position: absolute;
    left: 60px;
    top: 0;
  }
  .jia {
    height: 25px;
    font-size: 24px;
    position: absolute;
    left: 110px;
    top: 0;
  }
}
</style>
